package com.jmcgg.freesky.common.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

public class FTPUtil {

	private static Logger logger = Logger.getLogger(FTPUtil.class);
	public FTPClient ftp;
	public ArrayList<String> arFiles;

	public FTPUtil(boolean isPrintCommmand) {
		ftp = new FTPClient();
		arFiles = new ArrayList<String>();
		if (isPrintCommmand) {
			ftp.addProtocolCommandListener(new PrintCommandListener(
					new PrintWriter(System.out)));
		}
	}

	public boolean login(String host, int port, String username, String password)
			throws IOException {
		this.ftp.connect(host, port);
		if (FTPReply.isPositiveCompletion(this.ftp.getReplyCode())) {
			if (this.ftp.login(username, password)) {
				this.ftp.setControlEncoding("GBK");
				return true;
			}
		}
		if (this.ftp.isConnected()) {
			this.ftp.disconnect();
		}
		return false;
	}

	public void disConnection() throws IOException {
		if (this.ftp.isConnected()) {
			this.ftp.disconnect();
		}
	}

	public void List(String pathName) throws IOException {
		if (pathName.startsWith("/") && pathName.endsWith("/")) {
			String directory = pathName;
			this.ftp.changeWorkingDirectory(directory);
			FTPFile[] files = this.ftp.listFiles();
			for (FTPFile file : files) {
				if (file.isFile()) {
					arFiles.add(directory + file.getName());
				} else if (file.isDirectory()) {
					List(directory + file.getName() + "/");
				}
			}
		}
	}

	public void List(String pathName, String ext) throws IOException {
		if (pathName.startsWith("/") && pathName.endsWith("/")) {
			String directory = pathName;
			this.ftp.changeWorkingDirectory(directory);
			FTPFile[] files = this.ftp.listFiles();
			for (FTPFile file : files) {

				if (file.isFile()) {
					if (file.getName().endsWith(ext)) {
						arFiles.add(directory + file.getName());
						logger.info(directory + file.getName());
					}
				}
				if (file.isDirectory()) {
					if (!file.getName().equals(".")
							&& (!file.getName().equals(".."))) { // 注意这里的判断，否则会出现死循环！！！！
						List(directory + file.getName() + "/", ext);
					}
				}
			}
		}
	}

	public static void main(String[] args) throws IOException {
		FTPUtil f = new FTPUtil(true);
		// ftp.software.ibm.com: 170.225.15.40
		if (f.login("ftp.software.ibm.com", 21, "anonymous", "")) {
			f.List("/software/websphereportal/");
		}
		f.disConnection();

		for (String str : f.arFiles) {
			logger.info(str);
		}
	}
}
